package com.kma.summer2012.client.presenters.viewmap;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.datepicker.client.DatePicker;
import com.kma.summer2012.client.CrumbsEventBus;
import com.kma.summer2012.client.constants.ConstantsHolder;
import com.kma.summer2012.client.events.FillViewMapEvent;
import com.kma.summer2012.client.events.ListOfIdEvent;
import com.kma.summer2012.client.events.RequestInfoForMapEvent;
import com.kma.summer2012.client.events.request.MainPageEvent;
import com.kma.summer2012.client.presenters.Presenter;
import com.kma.summer2012.client.services.viewMap.CrumbsViewMapService;
import com.kma.summer2012.client.styles.style2.Recources;
import com.kma.summer2012.client.view.viewmap.MyTable;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class ViewMapPresenter implements Presenter {

    public interface Display {
        public MyTable getViewMapTable();

        public String getCellStyleName(int row, int column);

        public void setCellStyleName(int row, int column, String name);

        public Date getDateFromCalendar();

        public DatePicker getCalendar();

        public void setDateLabel(String date);

        public Button getBackButton();

        Widget asWidget();

    }

    private final Display display;

    public SimpleEventBus getEventBus() {
        return eventBus;
    }

    private SimpleEventBus eventBus = new SimpleEventBus();

    public ViewMapPresenter(Display display) {
        this.display = display;
        bind();
        this.display.setDateLabel(DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SHORT()).format(new Date()));
        setListOfRequestsId();
    }

    private void bind() {
        this.display.getBackButton().addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent clickEvent) {
                CrumbsEventBus.getInstance().fireEvent(new MainPageEvent());
            }
        });

        display.getCalendar().addValueChangeHandler(new ValueChangeHandler<Date>() {

            @Override
            public void onValueChange(ValueChangeEvent<Date> event) {
                Date date = event.getValue();
                String dateString = DateTimeFormat.getFormat("dd/MM/yyyy").format(date);
                //display.setDateLabel(dateString);
                setListOfRequestsId();

            }
        });

        ViewMapPresenter.this.eventBus.addHandler(FillViewMapEvent.getType(), new FillViewMapEvent.FillViewMapEventHandler() {
            @Override
            public void onFillViewMap(FillViewMapEvent event) {
                ViewMapPresenter.this.setViewMap(event.date);
            }
        });


        ViewMapPresenter.this.eventBus.addHandler(RequestInfoForMapEvent.getType(), new RequestInfoForMapEvent.RequestInfoForMapEventHandler() {
            @Override
            public void onRequestInfoForMap(RequestInfoForMapEvent event) {
                ViewMapPresenter.this.setViewMap(display.getDateFromCalendar());
                System.out.println("event.requestInfoMap" + event.requestInfoMap);
                display.getViewMapTable().setRequestInfoMap(event.requestInfoMap);
            }
        });

        ViewMapPresenter.this.eventBus.addHandler(ListOfIdEvent.getType(), new ListOfIdEvent.ListOfIdEventHandler() {
            @Override
            public void onListOfId(ListOfIdEvent event) {
                getInfoForPopup(event.requestIdList);
                System.out.println("event.requestIdList" + event.requestIdList);
            }
        });

    }

    @Override
    public void go(HasWidgets container) {
        container.clear();
        container.add(display.asWidget());
    }

    public void setViewMap(Date date) {
        display.setDateLabel(DateTimeFormat.getFormat(ConstantsHolder.getConstants().DATE_FORMAT_SHORT()).format(date));
        CrumbsViewMapService.App.getInstance().getViewMap(date, new AsyncCallback<Map<String, List<Integer>>>() {
            public void onFailure(Throwable caught) {
                //Window.alert("Error in CrumbsViewMapService.App.getInstance().getViewMap");
            }

            public void onSuccess(Map<String, List<Integer>> result) {
                setViewMapHeader();
                int row = 0;
                for (Map.Entry<String, List<Integer>> entry : result.entrySet()) {
                    display.getViewMapTable().getFlexCellFormatter().setColSpan(row + 1, 0, 10);
                    display.getViewMapTable().setText(row + 1, 0, entry.getKey());
                    row += setRequestRowAndColour(row + 1, entry) + 1;

                }
            }
        });


    }

    public void setViewMapHeader() {
        display.getViewMapTable().removeAllRows();
        display.getViewMapTable().setStyleName(Recources.INSTANCE.styles().grid());
        display.getViewMapTable().setText(0, 0, "Engineer-Requests / Time");
        display.getViewMapTable().setText(0, 1, " 9:00");
        display.getViewMapTable().setText(0, 2, "10:00");
        display.getViewMapTable().setText(0, 3, "11:00");
        display.getViewMapTable().setText(0, 4, "12:00");
        display.getViewMapTable().setText(0, 5, "13:00");
        display.getViewMapTable().setText(0, 6, "14:00");
        display.getViewMapTable().setText(0, 7, "15:00");
        display.getViewMapTable().setText(0, 8, "16:00");
        display.getViewMapTable().setText(0, 9, "17:00");
    }

    public int setRequestRowAndColour(int row, Map.Entry<String, List<Integer>> entry) {
        int countRow = 0;
        for (int i = 0; i < entry.getValue().size(); i++) {
            if (i % 4 == 0) {
                int hour = entry.getValue().get(i);
                if (entry.getValue().get(i + 2) == 2 || entry.getValue().get(i + 2) == 3 || entry.getValue().get(i + 2) == 4) {
                    display.getViewMapTable().insertRow(row + 1);
                    display.getViewMapTable().setText(row + 1, 0, "Request №" + entry.getValue().get(i + 3).toString());
                    display.setCellStyleName(row + 1, 0, Recources.INSTANCE.styles().grid2());
                    countRow += 1;
                    int r = entry.getValue().get(i + 1) - entry.getValue().get(i);
                    display.getViewMapTable().getFlexCellFormatter().setColSpan(row + 1, hour - 8, r);
                    if (entry.getValue().get(i + 2) == 3)
                        display.setCellStyleName(row + 1, hour - 8, Recources.INSTANCE.styles().forViewMap());
                    if (entry.getValue().get(i + 2) == 2)
                        display.setCellStyleName(row + 1, hour - 8, Recources.INSTANCE.styles().forViewMapYell());
                    if (entry.getValue().get(i + 2) == 4)
                        display.setCellStyleName(row + 1, hour - 8, Recources.INSTANCE.styles().forViewMapOrange());
                    for (int k = 1; k <= (10 - r); k++)
                        display.getViewMapTable().setHTML(row + 1, k, "&nbsp;");
                }
            }
        }
        return countRow;
    }

    public void getInfoForPopup(List<Integer> listOfRequestsId) {
        CrumbsViewMapService.App.getInstance().getRequestInfoMap(listOfRequestsId, new AsyncCallback<Map<Integer, String>>() {
            @Override
            public void onFailure(Throwable throwable) {
                System.out.println("Fail");
            }

            @Override
            public void onSuccess(Map<Integer, String> integerStringMap) {
                ViewMapPresenter.this.eventBus.fireEvent(new RequestInfoForMapEvent(integerStringMap));
                System.out.println("integerStringMap" + integerStringMap);
            }
        });

    }

    public void setListOfRequestsId() {
        final List<Integer> listId = new ArrayList<Integer>();
        CrumbsViewMapService.App.getInstance().getViewMap(display.getDateFromCalendar(), new AsyncCallback<Map<String, List<Integer>>>() {
            public void onFailure(Throwable caught) {
                //Window.alert("Error in CrumbsViewMapService.App.getInstance().getViewMap");
            }

            public void onSuccess(Map<String, List<Integer>> result) {
                for (Map.Entry<String, List<Integer>> entry : result.entrySet()) {
                    for (int i = 3; i < entry.getValue().size(); i += 4)
                        listId.add(entry.getValue().get(i));
                }
                System.out.println("listId" + listId);
                ViewMapPresenter.this.eventBus.fireEvent(new ListOfIdEvent(listId));
            }
        });
    }


}